#include <stdio.h>
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include <freertos/task.h>
#include <dht.h>  // 包含esp_dht库的头文件
#define DHT_GPIO_PIN GPIO_NUM_21  // DHT 数据引脚连接到 GPIO 21

//wifi模块
void test_esp_event_cb(void* event_handler_arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* getInfoStruct = (ip_event_got_ip_t*)event_data;
        esp_ip4_addr_t ip = getInfoStruct->ip_info.ip;
        printf("get ip success! " IPSTR "\n", IP2STR(&ip));
    }
}

void init_wifi()
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    // 注册事件回调
    esp_event_handler_instance_t wifi_event_handler;
    esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, test_esp_event_cb, NULL, &wifi_event_handler);
    esp_event_handler_instance_t ip_event_handler;
    esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, test_esp_event_cb, NULL, &ip_event_handler);

    // WiFi的配置与启动
    wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&config);

    esp_wifi_set_mode(WIFI_MODE_STA);
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = "Xiaomi 13",
            .password = "Qc263611",
        },
    };
    esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
    esp_wifi_start();
}

// 温湿度模块
void read_dht_task(void *pvParameter) {
    while (1) {
        float temperature = 0;
        float humidity = 0;

        // 读取 DHT11 传感器数据
        esp_err_t res = dht_read_float_data(DHT_TYPE_DHT11, DHT_GPIO_PIN, &humidity, &temperature);
        if (res == ESP_OK) {
            printf("Temperature: %.1f°C, Humidity: %.1f%%\n", temperature, humidity);
        } else {
            printf("Failed to read DHT11 sensor\n");
        }

        // 每2秒读取一次
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}

void app_main(void)
{
    // 创建任务来处理 DHT11 数据读取
    xTaskCreate(read_dht_task, "read_dht_task", 2048, NULL, 5, NULL);
    init_wifi();
    while(1)
    {
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}